package com.cbtx.module_sp.ui.fragment

import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import com.cbtx.module.base.ui.BaseVMFragment
import com.cbtx.module.common.ui.RenZhengAdapter
import com.cbtx.module_sp.ui.vm.RenZhengFragmentVM
import com.cbtx.module_sp.MyApplication
import com.cbtx.module_sp.R
import com.cbtx.module_sp.ui.activity.RenZhengDetailActivity
import com.txcb.lib.base.utils.LogUtil
import com.txcb.lib.base.view.SpaceItemDecoration
import kotlinx.android.synthetic.main.sp_fragment_renzheng.*

class GoodsAuthFragment : BaseVMFragment<RenZhengFragmentVM>() {


    var mAdapter: RenZhengAdapter? = null

    override fun getPresenterClazz(): Class<RenZhengFragmentVM> {
        return RenZhengFragmentVM::class.java
    }

    override fun setLayout(): Any {
        return R.layout.sp_fragment_renzheng
    }

    override fun initView(view: View?, savedInstanceState: Bundle?) {
        mTvCode.text = "云屏编码:${MyApplication.mAndroidId}"
        mVM.init()

        mAdapter = RenZhengAdapter(R.layout.sp_item_renzheng, mVM.mDatas)
        mRvRenZheng.layoutManager = GridLayoutManager(activity, 3)
        mRvRenZheng.addItemDecoration(SpaceItemDecoration(16))
        mRvRenZheng.adapter = mAdapter
//
        mVM.mLoaderStatus.observe(this, Observer {
            if (it == mVM.loadFirst) {
                //从缓存读取到的数据
                mAdapter?.notifyDataSetChanged()
            } else {
                mAdapter?.setEnableLoadMore(true)
                mRefreshView.isRefreshing = false

                mAdapter?.notifyDataSetChanged()
                if (mVM.mCanLoadMore) {
                    mAdapter?.loadMoreComplete()
                } else {
                    mAdapter?.loadMoreEnd()
                }
            }

        })
//
        LogUtil.d("initView : lazyFetchData")


        //加载更多
        mAdapter?.setOnLoadMoreListener({
            if (mVM.mCanLoadMore) {
                mVM.requestData(false)
            } else {
                mAdapter?.loadMoreEnd()
            }
        }, mRvRenZheng)


        //刷新
        mRefreshView.setOnRefreshListener {
            mVM.requestData(true)
        }

        mAdapter?.setOnItemClickListener { adapter, view, position ->
            val renZhengItem = mVM.mDatas?.get(position)
            RenZhengDetailActivity.start(activity!!, renZhengItem!!)
        }
    }


    override fun lazyData() {
        super.lazyData()

        mAdapter?.setEnableLoadMore(false)
        mVM.requestData(true)
    }
//    override fun lazyFetchData() {
//
//        LogUtil.d("RenZhengFragment : lazyFetchData")
//
//
//
//
//    }
//
//    override fun onMyViewClick(view: View) {
//
//    }


}